import jwt
from fastapi.security import OAuth2PasswordBearer
from fastapi import HTTPException, status
from datetime import datetime, timedelta
from appCustomers.config import SECRET_KEY
from appCustomers.utils.log_utils import logger

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# Функция для создания Bearer токена
def create_access_token(data: dict, expires_delta: timedelta):
    to_encode = data.copy()
    expire = datetime.now() + expires_delta
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm="HS256")
    return encoded_jwt

def create_standard_token(indata: dict):
    access_token_expires = timedelta(minutes=30)
    access_token = create_access_token(
        data=indata, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

def token_validate(token: str) -> HTTPException:
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        logger.info(f"Access granted: {payload}")
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")